package cn.hpclub.server.ext.fastexcel;

import java.io.OutputStream;
import java.util.List;

import com.jfinal.log.Logger;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;


public class FastExcelRender extends Render{
    protected final Logger LOG = Logger.getLogger(getClass());
    private final static String CONTENT_TYPE = "application/msexcel;charset=" + getEncoding();
    private List<?>[] data;
    private String[][] headers;
    private String[]   columns;
    private String[] sheetNames = new String[]{};
    private int cellWidth;

    private String fileName = "file1.xls";
    private int headerRow;
    private String version = "1.0";
    private AppendMoreData append;
    
    private OutputStream os = null;
    
    public FastExcelRender(List<?>[] data) {
        this.data = data;
    }
    public FastExcelRender(AppendMoreData append) {
        this.append = append;
    }
    public static FastExcelRender me(List<?>... data) {
        return new FastExcelRender(data);
    }
    @SuppressWarnings("unchecked")
    @Override
    public void render(){        
        try{
            if(os == null) {
                response.reset();
                response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
                response.setContentType(CONTENT_TYPE);
                os = response.getOutputStream();
            }
            FastExcelExporter.data(data).append(append).application(fileName).os(os).version(version).sheetNames(sheetNames).headers(headers).columns(columns).export();
        } catch (Exception e) {
            throw new RenderException(e);
        }
    }
    
    public FastExcelRender os(OutputStream os) {
        this.os = os;
        return this;
    }
    
    public FastExcelRender headers(String[]... headers) {
        this.headers = headers;
        return this;
    }

    public FastExcelRender headerRow(int headerRow) {
        this.headerRow = headerRow;
        return this;
    }

    public FastExcelRender columns(String...  columns) {
        this.columns = columns;
        return this;
    }

    public FastExcelRender sheetName(String... sheetName) {
        this.sheetNames = sheetName;
        return this;
    }

    public FastExcelRender cellWidth(int cellWidth) {
        this.cellWidth = cellWidth;
        return this;
    }

    public FastExcelRender fileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public FastExcelRender version(String version) {
        this.version = version;
        return this;
    }
    public FastExcelRender append(AppendMoreData append) {
        this.append = append;
        return this;
    }
    
    public interface AppendMoreData{
        List<?> append();
    }
}
